import { defineStore } from 'pinia'

export const useProjectStore = defineStore('project', {
    state: () => ({
        currentProject: {
            id: null,
            name: '',
            description: ''
        }
    }),
    actions: {
        setProjectInfo(project) {
            this.currentProject = project
            // 保存到 localStorage
            localStorage.setItem('currentProject', JSON.stringify(project))
        },
        clearProjectInfo() {
            this.currentProject = {
                id: null,
                name: '',
                description: ''
            }
            // 清除 localStorage
            localStorage.removeItem('currentProject')
        },
        // 从 localStorage 恢复项目信息
        restoreFromStorage() {
            const storedProject = localStorage.getItem('currentProject')
            if (storedProject) {
                try {
                    this.currentProject = JSON.parse(storedProject)
                    return true
                } catch (error) {
                    console.error('Failed to restore project from storage:', error)
                    return false
                }
            }
            return false
        },
        // 同步项目信息
        syncProjectInfo(routeParams) {
            // 如果 store 中没有数据，尝试从 localStorage 恢复
            if (!this.currentProject.id) {
                this.restoreFromStorage()
            }

            // 如果仍然没有数据，使用路由参数
            if (!this.currentProject.id && routeParams) {
                this.setProjectInfo({
                    id: routeParams.projectId,
                    name: routeParams.projectName,
                    description: routeParams.projectDescription
                })
            }
        }
    },
    getters: {
        getProjectInfo: (state) => state.currentProject
    }
})
